//
//  LGFollowOpinionController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/7/17.
//  处理意见

#import "LGMedicineBallFollowUpRecorder.h"
//药球--详情
#import "LGMedicineBallDetailController.h"

#import <MediaPlayer/MediaPlayer.h>
//#import <AVFoundation/AVFoundation.h>
#import "LGFollowHandleView.h"
#import "TUIAudioRecorder.h"
#import "TUIRecordView.h"
#import "TUIDefine.h"
#import "TUITool.h"
#import "TUIDefine.h"
#import "MCPlayer.h"
#import "TUIDefine.h"
@interface LGMedicineBallFollowUpRecorder ()<AVAudioRecorderDelegate>
/**   */
@property (nonatomic , strong)UIScrollView *scrollView;
/**  本次随访建议 */
@property (nonatomic , strong)LGFollowHandleView *opinionView;
/**  方案调整描述 */
@property (nonatomic , strong)LGFollowHandleView *planView;
/**  下次随访关注点 */
@property (nonatomic , strong)LGFollowHandleView *focusView;
/**   */
@property (nonatomic , strong)UIButton *saveBtn;

@property (nonatomic , strong)TUIRecordView *recordView;


//@property (nonatomic, strong)TUIAudioRecorder *recorder;
/**   */
@property (nonatomic , strong)AVAudioSession *session;
/**   */
@property (nonatomic , strong)AVAudioRecorder *recorder;
/**   */
@property (nonatomic , strong)NSMutableArray *opinionArray;
/**   */
@property (nonatomic , strong)NSMutableArray *planArray;
/**   */
@property (nonatomic , strong)NSMutableArray *focusArray;
/**   */
@property (nonatomic , copy)NSString *filePath;
/**   */
@property (nonatomic , assign)BOOL allowRecord;
/**   */
@property (nonatomic , strong)NSTimer *recordTimer;
/**   */
@property (nonatomic , strong)NSDate *recordStartTime;
/**   */
@property (nonatomic , assign)BOOL firstRecord;

@end

@implementation LGMedicineBallFollowUpRecorder

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.firstRecord = NO;
    [self createSubView];
    [self recordViewBlockAction];//Block回调
    if(_followid && _followid.length>0){
        //修改
        self.title = @"修改随访总结";
        [self requestData];
    }else{
        //添加
        self.title = @"添加随访总结";
        self.followid = @"";
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[MCPlayer shareManager] stopMedia];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.dcb.follow_up/getSummary" parameters:@{@"followup_id":self.followid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.planid = LGNSString(returnData[@"dcb_plan_id"]);
            self.patientid = LGNSString(returnData[@"patient_id"]);
            
            self.opinionView.content = LGNSString(returnData[@"opinion"]);
            self.opinionArray = returnData[@"opinion_files"];
            self.opinionView.recordArray = self.opinionArray;
            
            self.planView.content = LGNSString(returnData[@"plan_adjustment"]);
            self.planArray = returnData[@"plan_adjustment_files"];
            self.planView.recordArray = self.planArray;
            
            self.focusView.content = LGNSString(returnData[@"next_follow"]);
            self.focusArray = returnData[@"next_follow_files"];
            self.focusView.recordArray = self.focusArray;
            [self performSelector:@selector(refreshHeight) withObject:nil afterDelay:0.3];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)refreshHeight{
    self.scrollView.contentSize = CGSizeMake(Screen_W, kMaxY(self.focusView.frame)+viewPix(10));
}

//recordView的Block回调
-(void)recordViewBlockAction{
    __weak typeof(self) weakSelf = self;
    //录音View高度变化
    self.opinionView.recordViewHeightChanged = ^(CGFloat height) {
        [weakSelf.opinionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(height));
        }];
        weakSelf.scrollView.contentSize = CGSizeMake(Screen_W, height+viewPix(48)+weakSelf.planView.size.height+weakSelf.focusView.size.height+viewPix(10));
    };
    
    self.planView.recordViewHeightChanged = ^(CGFloat height) {
        [weakSelf.planView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(height));
        }];
        weakSelf.scrollView.contentSize = CGSizeMake(Screen_W, height+viewPix(48)+weakSelf.opinionView.size.height+weakSelf.focusView.size.height+viewPix(10));
    };
    
    self.focusView.recordViewHeightChanged = ^(CGFloat height) {
        [weakSelf.focusView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@(height));
        }];
        weakSelf.scrollView.contentSize = CGSizeMake(Screen_W, height+viewPix(48)+weakSelf.opinionView.size.height+weakSelf.planView.size.height+viewPix(10));
    };
    
    //播放录音
    self.opinionView.startPlayVoice = ^{
        [weakSelf.planView stopPlayVoice];
        [weakSelf.focusView stopPlayVoice];
    };
    self.planView.startPlayVoice = ^{
        [weakSelf.opinionView stopPlayVoice];
        [weakSelf.focusView stopPlayVoice];
    };
    self.focusView.startPlayVoice = ^{
        [weakSelf.opinionView stopPlayVoice];
        [weakSelf.planView stopPlayVoice];
    };
    
    //删除录音
    self.opinionView.removeRecordData = ^(NSInteger index) {
        [weakSelf.opinionArray removeObjectAtIndex:index];
        weakSelf.opinionView.recordArray = weakSelf.opinionArray;
    };
    self.planView.removeRecordData = ^(NSInteger index) {
        [weakSelf.planArray removeObjectAtIndex:index];
        weakSelf.planView.recordArray = weakSelf.planArray;
    };
    self.focusView.removeRecordData = ^(NSInteger index) {
        [weakSelf.focusArray removeObjectAtIndex:index];
        weakSelf.focusView.recordArray = weakSelf.focusArray;
    };
}

//开始录音
- (void)onRecordButtonTouchDown:(UIButton *)sender{
    self.allowRecord = NO;
    
    @weakify(self)
    [self requestRecordAuthorization:^(BOOL first, BOOL granted) {
        @strongify(self)
        if(first == NO && granted == NO){
            //拒绝录音--弹框去开启录音
            [self showRecordAuthorizationAlert];
        }else if(first == NO && granted == YES){
            //允许录音
            self.allowRecord = YES;
            [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
            [[AVAudioSession sharedInstance] setActive:YES error:nil];
            
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"record_file"];
            // 判断文件夹是否存在
            if(![[[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil] count]){
                [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            }
            self.filePath = [path stringByAppendingPathComponent:@"/record.m4a"];
            NSDictionary *recordSetting = [[NSDictionary alloc]
                initWithObjectsAndKeys:
                        [NSNumber numberWithFloat:16000.0], AVSampleRateKey,
                        [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                        [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                        [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                        [NSNumber numberWithInt:AVAudioQualityHigh], AVEncoderAudioQualityKey, nil];

            self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:self.filePath] settings:recordSetting error:nil];
            self.recorder.meteringEnabled = YES;
            [self.recorder prepareToRecord];
            [self.recorder record];
            [self.recorder updateMeters];
            self.recordStartTime = [NSDate date];
            self.recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onRecordTimerTriggered:) userInfo:nil repeats:YES];
            [self.view.window addSubview:self.recordView];
        }
    }];
}


//录音计时器
-(void)onRecordTimerTriggered:(NSTimer *)timer{
    [self.recorder updateMeters];
    float power = [self.recorder averagePowerForChannel:0];
    [self.recordView setPower:power];
}

//结束录音
- (void)onRecordButtonTouchUpInside:(UIButton *)sender{
    if(!_recordTimer){
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [self.recorder stop];
            if (self.recordTimer) {
                [self.recordTimer invalidate];
                self.recordTimer = nil;
            }
            [self.recordView setStatus:Record_Status_TooShort];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                [UIView animateWithDuration:0.3 animations:^{
                    self.recordView.alpha = 0;
                } completion:^(BOOL finished) {
                    [self.recordView removeFromSuperview];
                    self.recordView = nil;
                }];
            });
        });
    }else{
        [self.recorder stop];
        if (_recordTimer) {
            [self.recordTimer invalidate];
            self.recordTimer = nil;
        }
        NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.recordStartTime];
        @weakify(self);
        if (interval == NAN || interval < 1) {
            [self.recordView setStatus:Record_Status_TooShort];

        }else{
            self.recordView.title.text = @"录音完成";
            self.recordView.title.backgroundColor = [UIColor clearColor];
            [self saveRecordData:sender];
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            [UIView animateWithDuration:0.3 animations:^{
                self.recordView.alpha = 0;
            } completion:^(BOOL finished) {
                [self.recordView removeFromSuperview];
                self.recordView = nil;
            }];
        });
    }
}



//保存录音数据
-(void)saveRecordData:(UIButton *)sender{
    if(self.allowRecord == NO) return;
    __block NSInteger index = sender.tag;
    NSData *data = [NSData dataWithContentsOfFile:self.filePath];
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.filePath] options:nil];
    __block CGFloat second = CMTimeGetSeconds(asset.duration);
    [RequestUtil uploadVoice:@"/doctor/upload/audio" parameters:@{@"to_text":@"1"} withSign:YES voiceData:@[data] success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSDictionary *tempDic = @{@"duration":[NSString stringWithFormat:@"%.f",second],@"url":LGNSString(returnData[@"url"]),@"text":LGNSString(returnData[@"text"]),@"uri":LGNSString(returnData[@"uri"])};
            [[NSFileManager defaultManager] removeItemAtPath:self.filePath error:nil];
            if(index == 1000){
                //随访意见
                [self.opinionArray addObject:tempDic];
                self.opinionView.recordArray = self.opinionArray;
            }else if (index == 1001){
                //方案调整
                [self.planArray addObject:tempDic];
                self.planView.recordArray = self.planArray;
            }else{
                //关注点
                [self.focusArray addObject:tempDic];
                self.focusView.recordArray = self.focusArray;
            }
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } failure:^(NSError *error) {
        [TooltipView showMessage:@"保存失败" offset:0];
    }];
}


//保存数据
-(void)saveBtnAction{
    NSString *opinion = (self.opinionView.content && self.opinionView.content.length>0)?self.opinionView.content:@"";
    NSString *planString = (self.planView.content && self.planView.content.length>0)?self.planView.content:@"";
    NSString *focusString = (self.focusView.content && self.focusView.content.length>0)?self.focusView.content:@"";
    if(opinion.length == 0 && self.opinionArray.count == 0 && planString.length == 0 && self.planArray.count == 0 && focusString.length == 0 && self.focusArray.count == 0){
        [TooltipView showMessage:@"请输入总结内容" offset:0];
        return;
    }

    [RequestUtil withPOST:@"/doctor/patient.dcb.follow_up/saveSummary" parameters:@{@"plan_id":self.planid,@"patient_id":self.patientid,@"followup_id":self.followid,@"opinion":opinion,@"opinion_file":self.opinionArray,@"plan_adjustment":planString,@"plan_adjustment_file":self.planArray,@"next_follow":focusString,@"next_follow_file":self.focusArray} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [TooltipView showMessage:@"保存成功" offset:0];
            for (UIViewController *controller in self.navigationController.childViewControllers) {
                //药球详情
                if([controller isKindOfClass:[LGMedicineBallDetailController class]]){
                    [self.navigationController popToViewController:controller animated:YES];
                    return;
                }
            }
            if(self.opinionSaveSuccess){
                self.opinionSaveSuccess(returnData);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"保存失败，请重试" offset:0];
    }];
}

-(void)onRecordButtonTouchCancel:(UIButton *)sender{
    if ([self.recorder isRecording]) [self.recorder stop];
    if (_recordTimer) {
        [self.recordTimer invalidate];
        self.recordTimer = nil;
    }
    [self.recordView removeFromSuperview];
    self.recordView = nil;
}

//上滑结束
- (void)onRecordButtonTouchDragExit:(UIButton *)sender{
    [self.recordView setStatus:Record_Status_Cancel];
}

//滑入录音
- (void)onRecordButtonTouchDragEnter:(UIButton *)sender{
    [self.recordView setStatus:Record_Status_Recording];
}


//请求录音权限
- (void)requestRecordAuthorization:(void (^)(BOOL first , BOOL granted))response {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    AVAudioSessionRecordPermission permission = session.recordPermission;
    if (permission == AVAudioSessionRecordPermissionUndetermined) {
        [session requestRecordPermission:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (response) {
                    response(YES,NO);
                }
            });
        }];
    } else if (permission == AVAudioSessionRecordPermissionGranted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(NO,YES);
            }
        });
    } else if (permission == AVAudioSessionRecordPermissionDenied) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (response) {
                response(NO,NO);
            }
        });
    }
}

//开启权限弹框
- (void)showRecordAuthorizationAlert{
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:TUIKitLocalizableString(TUIKitInputNoMicTitle) message:TUIKitLocalizableString(TUIKitInputNoMicTips) preferredStyle:UIAlertControllerStyleAlert];
    [controller tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitInputNoMicOperateLater) style:UIAlertActionStyleCancel handler:nil]];
    [controller tuitheme_addAction:[UIAlertAction actionWithTitle:TUIKitLocalizableString(TUIKitInputNoMicOperateEnable) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
    }]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:controller animated:YES completion:nil];
    });
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.title = @"修改随访总结";
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.opinionView];
    [self.scrollView addSubview:self.planView];
    [self.scrollView addSubview:self.focusView];
    [self.view addSubview:self.saveBtn];
    [self.opinionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(viewPix(16));
        make.left.equalTo(self.view).offset(viewPix(16));
        make.right.equalTo(self.view).offset(-viewPix(10));
        make.height.equalTo(@(viewPix(150)));
    }];
    [self.planView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.opinionView.mas_bottom).offset(viewPix(16));
        make.left.right.equalTo(self.opinionView);
        make.height.equalTo(@(viewPix(150)));
    }];
    [self.focusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.planView.mas_bottom).offset(viewPix(16));
        make.left.right.equalTo(self.opinionView);
        make.height.equalTo(@(viewPix(150)));
    }];
    
}

-(NSMutableArray *)opinionArray{
    if(!_opinionArray){
        _opinionArray = [NSMutableArray array];
    }
    return _opinionArray;
}

-(NSMutableArray *)planArray{
    if(!_planArray){
        _planArray = [NSMutableArray array];
    }
    return _planArray;
}

-(NSMutableArray *)focusArray{
    if(!_focusArray){
        _focusArray = [NSMutableArray array];
    }
    return _focusArray;
}


-(UIScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(85))];
        _scrollView.backgroundColor = [UIColor clearColor];
    }
    return _scrollView;
}

-(LGFollowHandleView *)opinionView{
    if(!_opinionView){
        _opinionView = [[LGFollowHandleView alloc] init];
        [_opinionView setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 2) opacity:0.15 radius:viewPix(15)];
        _opinionView.backgroundColor = [UIColor whiteColor];
        _opinionView.titleLabel.text = @"本次随访意见";
        _opinionView.recordBtn.tag = 1000;
        [_opinionView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_opinionView.recordBtn addTarget:self action:@selector(onRecordButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_opinionView.recordBtn addTarget:self action:@selector(onRecordButtonTouchCancel:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchCancel];
        [_opinionView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [_opinionView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _opinionView;
}

-(LGFollowHandleView *)planView{
    if(!_planView){
        _planView = [[LGFollowHandleView alloc] init];
        [_planView setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 2) opacity:0.15 radius:viewPix(15)];
        _planView.backgroundColor = [UIColor whiteColor];
        _planView.titleLabel.text = @"方案调整描述";
        _planView.recordBtn.tag = 1001;
        [_planView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_planView.recordBtn addTarget:self action:@selector(onRecordButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_planView.recordBtn addTarget:self action:@selector(onRecordButtonTouchCancel:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchCancel];
        [_planView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [_planView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _planView;
}

-(LGFollowHandleView *)focusView{
    if(!_focusView){
        _focusView = [[LGFollowHandleView alloc] init];
        [_focusView setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 2) opacity:0.15 radius:viewPix(15)];
        _focusView.backgroundColor = [UIColor whiteColor];
        _focusView.titleLabel.text = @"下次随访关注点";
        _focusView.recordBtn.tag = 1002;
        [_focusView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_focusView.recordBtn addTarget:self action:@selector(onRecordButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [_focusView.recordBtn addTarget:self action:@selector(onRecordButtonTouchCancel:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchCancel];
        [_focusView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [_focusView.recordBtn addTarget:self action:@selector(onRecordButtonTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _focusView;
}

-(UIButton *)saveBtn{
    if(!_saveBtn){
        _saveBtn = [UIButton buttonWithTitle:@"保存" topMargin:Screen_H-topBarHeight-viewPix(82)];
        [_saveBtn addTarget:self action:@selector(saveBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}

- (TUIRecordView *)recordView{
    if (!_recordView) {
        _recordView = [[TUIRecordView alloc] init];
        _recordView.frame = [UIScreen mainScreen].bounds;
    }
    return _recordView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
